import React from 'react'
import { useRef } from 'react'
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import {addGoods } from '../store/slice/goods'
export default function AddGoods() {
    // 创建dispatch函数
    const dispatch = useDispatch()
    // 路由跳转函数
    const navigate = useNavigate()
    const addGoodsHandler = (e) => {
        // 1. 阻止默认行为
        e.preventDefault()
        // 2. 获取文本框内容
        let gname = gnameRef.current.value.trim()
        let price = priceRef.current.value.trim()
        // 3. 组合一个新的商品对象
        let goods = {gname,price}
        // 4. 添加到redux
        dispatch(addGoods(goods))
        // 5. 跳转到商品列表
        navigate('/goodsList')
    }
    const gnameRef = useRef()
    const priceRef = useRef()
    return (
        <div>
            <h3>添加商品</h3>
            <form action="" onSubmit={addGoodsHandler}>
                <p>商品名称: <input type="text" ref={gnameRef} name="" id="" /></p>
                <p>商品价格: <input type="text" ref={priceRef} name="" id="" /></p>
                <p><button>添加</button></p>
            </form>
        </div>
    )
}
